import { Injectable } from '@nestjs/common';
import * as path from 'path';

@Injectable()
export class ImageUploadService {
  /**
   * 单个图片上传
   * @param params
   * @param file
   */
  async upload(params, file) {
    let matchRes = path.parse(file.path).dir.match(/images\\(.*)$/);
    let url = null;
    if (matchRes && matchRes.length > 1) {
      url = '/linxi/' + matchRes[1].replace(/\\/g, '/') + '/' + file.filename;
    }
    return {
      params,
      originalname: file.originalname,
      filename: file.filename,
      size: file.size,
      mimeType: file.mimetype,
      ext: path.parse(file.path).ext,
      url,
    };
  }

  /**
   * 多个图片上传
   * @param params
   * @param files
   */
  async uploadFiles(params, files) {
    let fileList = files.map((file) => {
      let matchRes = path.parse(file.path).dir.match(/images\\(.*)$/);
      let url = null;
      if (matchRes && matchRes.length > 1) {
        url = '/linxi/' + matchRes[1].replace(/\\/g, '/') + '/' + file.filename;
      }
      return {
        originalname: file.originalname,
        filename: file.filename,
        size: file.size,
        mimeType: file.mimetype,
        ext: path.parse(file.path).ext,
        url,
      };
    });
    return {
      params,
      fileList,
    };
  }
}
